package cn.tedu.csmall.passport.config;

import cn.tedu.csmall.commons.web.ServiceCode;
import cn.tedu.csmall.passport.filter.JwtAuthorizationFilter;
import cn.tedu.csmall.commons.web.JsonResult;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@Configuration
@Slf4j
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    @Autowired
    JwtAuthorizationFilter jwtAuthorizationFilter;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.exceptionHandling().authenticationEntryPoint(new AuthenticationEntryPoint() {
            @Override
            public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
                String message = "您未登录，请先登录去！";
                JsonResult fail = JsonResult.fail(ServiceCode.ERR_UNAUTHORIZED, message);

                String s = JSON.toJSONString(fail);

                response.setContentType("application/json; charset=utf-8");
                PrintWriter writer = response.getWriter();
                writer.println(s);
                writer.close();
            }
        });

        http.csrf().disable();
        http.cors();

        String[] urls = {
                "/doc.html",
                "/**/*.css",
                "/**/*.js",
                "swagger-resources",
                "/v2/api-docs",
                "/admin/login"
        };
        http.authorizeRequests()
//                .mvcMatchers(HttpMethod.OPTIONS, "/**")
//                .permitAll()
                .mvcMatchers(urls)
                .permitAll()
                .anyRequest()
                .authenticated();

//        super.configure(http);
//        http.formLogin();

        http.addFilterBefore(jwtAuthorizationFilter, UsernamePasswordAuthenticationFilter.class);

        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }
}
